/**
 * Created by DevilsEyes on 2016/3/14.
 */
'use strict';
define(['wx'], function (wx) {
    var PageController = {
        nowpage: '',
        oldpage: '',
        timer: null,
        timerOn: function () {
            this.oldpage = this.nowpage;
            var c = this;
            this.timer = setInterval(function () {

                if (c.nowpage != c.oldpage) {
                    c.timerOff();
                } else {
                    if (window.scrollY > 0 && c.nowpage) {
                        db.set('HEIGHT_' + c.nowpage, window.scrollY);
                    }
                }
            }, 50);
        },
        timerOff: function () {
            clearInterval(this.timer);
        }
    };

    function Page(params) {

        this.$id = params.$id;

        if (params.$model) {
            for (var key in params.$model) {
                this[key] = params.$model[key];
            }
        }

        //初始化页面
        this.$init = function (option) {

            option = option || {};
            PageController.nowpage = this.$id;
            require(['logger', 'payment'], function (logger, payment) {
                logger.close();
                //
                payment.close();
            });

            //就算没有Title也应当清空原有title
            this.setTitle(option.setTitle || '');

            if (option.setShare)this.setShare(option.setShare);

        };

        //设置Title
        this.setTitle = function (title) {
            document.title = title;

            if (agent.isWechat) {
                var $body = $('body');

                // hack在微信等webview中无法修改document.title的情况
                var $iframe = $('<iframe src="/favicon.ico" style="display: none"></iframe>').on('load', function () {
                    setTimeout(function () {
                        $iframe.off('load').remove()
                    }, 0)
                }).appendTo($body);

            } else if (agent.isClient) {
                //todo 客户端设置Title
            }
        };

        //设置分享参数
        this.setShare = function (options) {

            if (agent.isWechat) {

                wx.ready(function () {
                    options.share === true ?
                        wx.shareAllow() : wx.closeAll()
                });

            } else if (agent.isClient) {
                //客户端分享
            }

        };

        this.bindEvent = function (EVENT, jQueryObject) {
            var event_extend = {
                goto: function (hash) {
                    location.hash = hash;
                }
            };

            var hash = {
                'i-tap': 'tapone',
                'i-keydown': 'keydown',
                'i-keyup': 'keyup',
                'i-change': 'change',
                's-tap': 'tap' //Iscroll特殊事件，避免与滚动冲突
            };

            EVENT = $.extend(EVENT, event_extend);

            jQueryObject = jQueryObject || $('#page');
            for (var eve in hash) {

                var $collect = $('[' + eve + ']', jQueryObject);
                if (jQueryObject.attr(eve))$collect = $collect.add(jQueryObject);

                $collect.each(function () {
                    var str, f, p;
                    str = $(this).attr(eve);
                    f = str.split('(')[0];
                    try {
                        p = str.match(/\(([^\)]*)\)/)[1];
                    } catch (e) {
                        p = null;
                    }
                    var func = function () {
                        EVENT[f].bind(this)(p);
                    };

                    $(this).bind(hash[eve], func);
                });
            }
        };

        this.bind$ = function ($model, jQueryObject) {
            jQueryObject = jQueryObject || $('#page');
            $model = $model || {};

            $('[i-dom]', jQueryObject).each(function () {
                var str;
                str = $(this).attr('i-dom');
                if ($model[str]) {
                    //console.log("WARNING:" + str + '已存在');
                }
                $model[str] = $(this);
            });
        };

        this.getLastPosition = function (bool) {
            this.done();
            if (bool === undefined || bool) {
                $(window).scrollTop(db.get('HEIGHT_' + this.$id));
                db.set('HEIGHT_' + this.$id, 0);
            } else {
                $(window).scrollTop();
            }
        };

        this.done = function () {
            PageController.timerOn();
        };

        this.isThisPage = function () {
            //检查是否仍在当前页面
            return PageController.nowpage == this.$id;
        };

        return this;
    }

    return {
        creat: Page,
        controller: PageController,
        getNowPage: function () {
            return PageController.nowpage
        }
    };
});